<template>
  <a-modal
    v-model:open="visible"
    title="修改密码"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="520px"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="新密码" name="newPassword">
        <a-input-password
          v-model:value="formData.newPassword"
          placeholder="请输入新密码"
          :maxlength="20"
        />
      </a-form-item>

      <a-form-item label="确认密码" name="checkPassword">
        <a-input-password
          v-model:value="formData.checkPassword"
          placeholder="请再次输入新密码"
          :maxlength="20"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { resetPassword } from '@/api/userController'

const props = defineProps<{
  open: boolean
}>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  'success': []
}>()

const formRef = ref<FormInstance>()
const loading = ref(false)

const formData = reactive<API.UserResetPasswordRequest>({
  newPassword: '',
  checkPassword: ''
})

// 验证两次密码是否一致
const validatePasswordMatch = async (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请确认新密码')
  }
  if (value !== formData.newPassword) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

const rules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度为8-20个字符', trigger: 'blur' }
  ],
  checkPassword: [
    { required: true, validator: validatePasswordMatch, trigger: 'blur' }
  ]
}

// 监听 open 变化，重置表单数据
watch(() => props.open, (newVal) => {
  if (newVal) {
    formData.newPassword = ''
    formData.checkPassword = ''
    // 延迟重置表单，确保表单已渲染
    setTimeout(() => {
      formRef.value?.resetFields()
    }, 0)
  }
})

// 计算属性，用于 v-model:open
const visible = computed({
  get: () => props.open,
  set: (val) => emit('update:open', val)
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    const res = await resetPassword({
      newPassword: formData.newPassword,
      checkPassword: formData.checkPassword
    })

    if (res.data.code === 0) {
      message.success('密码修改成功，请重新登录')
      emit('success')
      visible.value = false
    } else {
      message.error('密码修改失败：' + res.data.message)
    }
  } catch (error) {
    console.error('表单验证失败', error)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  formRef.value?.resetFields()
  formData.newPassword = ''
  formData.checkPassword = ''
  visible.value = false
}
</script>

<style scoped>
:deep(.ant-form-item-label > label) {
  font-weight: 500;
}
</style>
